import 'dart:async';

import 'package:fish_redux/fish_redux.dart';
import 'package:flutter/material.dart' hide Action;
import 'package:fluttertoast/fluttertoast.dart';
import 'package:member_center_sdk/core/sdk_enum.dart';
import 'package:member_center_sdk/sdk.dart';
import 'package:member_center_sdk_example/core/auth_type.dart';
import 'package:member_center_sdk_example/pages/members/login/action.dart';
import 'action.dart';
import 'state.dart';

Effect<SmsLoginState> buildEffect() {
  return combineEffects(<Object, Effect<SmsLoginState>>{
    SmsLoginAction.sms: _onSmsAction,
    Lifecycle.dispose: _onDispose,
    Lifecycle.initState: _onInit,
    SmsLoginAction.switchLgin: _onSwitchAction,
    SmsLoginAction.login: _onLoginAction,
  });
}

Timer _timer;

void _startTimer(Context<SmsLoginState> ctx) {
  _timer = Timer.periodic(Duration(seconds: 1), (timer) {
    if (ctx.state.remainSeconds > 0) {
      ctx.dispatch(
          SmsLoginActionCreator.onSetRemainAction(ctx.state.remainSeconds - 1));
    }
  });
}

void _onInit(Action action, Context<SmsLoginState> ctx) {
  _startTimer(ctx);
}

void _onDispose(Action action, Context<SmsLoginState> ctx) {
  _timer.cancel();
}

Future _onSmsAction(Action action, Context<SmsLoginState> ctx) async {
  var sdk = MemberCenterSdk.get();
  String phone = ctx.state.userNameController.text;
  ctx.dispatch(SmsLoginActionCreator.onSetRemainAction(120));
  ctx.dispatch(SmsLoginActionCreator.onLoadingAction(true));
  var sdkResult = await sdk.sendSms(SmsType.Auth, phone);
  ctx.dispatch(SmsLoginActionCreator.onLoadingAction(false));
  if (sdkResult.success) {
    sdk.setCacheUserName(1, phone);
    ctx.dispatch(SmsLoginActionCreator.onSetSmsId(sdkResult.smsId));
    Fluttertoast.showToast(msg: "发送成功");
  } else {
    Fluttertoast.showToast(msg: sdkResult.message);
  }
  ctx.dispatch(
      SmsLoginActionCreator.onSetRemainAction(sdkResult.remainSeconds));
  // ctx.dispatch(SmsLoginActionCreator.onSetRemainAction(5));
}

void _onSwitchAction(Action action, Context<SmsLoginState> ctx) {
  ctx.dispatch(MemberLoginActionCreator.onPwdLoginAction());
}

Future _onLoginAction(Action action, Context<SmsLoginState> ctx) async {
  if (ctx.state.smsId == null) {
    Fluttertoast.showToast(msg: "请先发送短信");
    return;
  }
  String code = ctx.state.codeController.text;
  var sdkResult = await MemberCenterSdk.get().smsAuth(AuthType.login.index,ctx.state.smsId, code);
  if (sdkResult.success) {
    Fluttertoast.showToast(msg: "登录成功");
    Navigator.of(ctx.context).pop(true);
  } else {
    Fluttertoast.showToast(msg: sdkResult.message);
  }
}
